<?php
namespace Think;

/**
 * 辅助类
 * Class Helper
 *
 * @package App\Libs
 */
class Helper
{

    /**
     * 获取当前购物的归属店铺ID
     *
     * @return int
     */
    public static function getBelongToShopId()
    {
        $belongToShopId = \App\Services\MicroShop::NOT_MICRO_SHOP_ID;
        if (\Framework\Libs\Http::$belongToShopId > 0) {
            $belongToShopId = \Framework\Libs\Http::$belongToShopId;
        }
        return $belongToShopId;
    }

    /**
     * 是否来自于微店
     *
     * @return boolean
     */
    public static function isFromMicroShop()
    {
        if (self::getBelongToShopId() > 0) {
            return true;
        }
        return false;
    }

    /**
     * 获取支付总价
     *
     * @param unknown_type $orderInfo
     *            订单信息
     */
    public static function getPayPrice($orderInfo)
    {
        $price = 0;
        $cost = isset($orderInfo['cost'])?$orderInfo['cost']:0;
        $totalPrice = isset($orderInfo['total_price'])?$orderInfo['total_price']:0;
        $cpnsPrice = isset($orderInfo['cpns_price'])?$orderInfo['cpns_price']:0;
        $freight = isset($orderInfo['freight'])?$orderInfo['freight']:0;
        $freightPrice = isset($orderInfo['freight_price'])?$orderInfo['freight_price']:0;
        $cashPrice = isset($orderInfo['cash_price'])?$orderInfo['cash_price']:0;
        $taxPrice = isset($orderInfo['tax_price'])?$orderInfo['tax_price']:0;
        $mstaxation = isset($orderInfo['total_ms_taxation'])?$orderInfo['total_ms_taxation']:0;
        $ms_Freight_risk = isset($orderInfo['ms_Freight_risk'])?$orderInfo['ms_Freight_risk']:0;
        if(!empty($orderInfo)){
            $price = ($cost ? $cost : $totalPrice) - $cpnsPrice + ($freight ? $freight : $freightPrice) + $mstaxation + $ms_Freight_risk + $taxPrice - $cashPrice;
        }
        
        return $price;
    }
    
    
    
    

    /**
     *
     * 产生随机字符串，不长于32位
     *
     * @param int $length            
     * @return 产生的随机字符串
     */
    public static function getNonceStr($length = 32)
    {
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i ++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    /**
     * 检查IP.
     * 格式为123.123.123.123
     *
     * @param unknown_type $ip            
     */
    public static function checkIp($ip)
    {
        if (! empty($ip) && preg_match('#^([\d]{1,3}\.){3}[\d]{1,3}$#', $ip))
            return true;
        return false;
    }

    /**
     * HTTP请求方法
     * 
     * @author gxd
     * @param unknown $durl            
     * @param unknown $data            
     * @return mixed
     */
    public static function curl_file_get_contents($durl, $data = array(), $header = array())
    {
        $ch = curl_init();
        if (! empty($header)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        }else{
            $header [] = "content-type: application/json; charset=UTF-8";
        }
        
        curl_setopt($ch, CURLOPT_URL, $durl);
        curl_setopt($ch, CURLOPT_TIMEOUT, 15);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
        curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        
        if (! empty($data)) {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($ch, CURLOPT_HEADER, 0);
        $r = curl_exec($ch);
        if ($r) {
            curl_close($ch);
            return $r;
        } else {
            $error = curl_errno($ch);
            curl_close($ch);
            return 'error:' . $error;
        }
    }
    
    /**
     * 获取平台和系统值
     */
    public static function getClientPlatformAndSystem(){
        $headerClientSystem = \Framework\Libs\Http::$clientSystem;
        $clientSystem = 0;
        $clientPlatform = 0;
        switch ($headerClientSystem)
        {
            case 'ios':
                $clientSystem = 1;
                $clientPlatform = 1;
                break;
            case 'android':
                $clientSystem = 2;
                $clientPlatform = 1;
                break;
            case 'wx-micro-shop':
                $clientSystem = 3;
                $clientPlatform = 4;
                break;
            case 'web-pc':
                $clientSystem = 3;
                $clientPlatform = 3;
                break;
            case 'web-wap':
                $clientSystem = 3;
                $clientPlatform = 2;
                break;
            default:
                break;
        }
        
        return ['clientSystem'=>$clientSystem,'clientPlatform'=>$clientPlatform];
    }
    
    /**
     * 调用后台
     * @param unknown $urlKey
     * @param unknown $data
     * @param unknown $createAccessKeyParam用来生成密钥的变量值
     */
    public static function callAdminHaioo($urlKey,$data,$createAccessKeyParam){
        $repeatTime =3;//失败重试次数
        //获取token
        if(isset($data['trade_no'])){
            if(RUN_MOD == "test"){
                $url = "http://test-admin.52ywy.com/notify/cod.php";
                $access_key = "g4qxpmccrcc69jrtrydf8gvb9tkx2uz1";
            }else{
                $url = \App\Config\Payment::instance()->cod['notify_url'];
                $access_key = \App\Config\Payment::instance()->cod['key'];
            }
        }else{
            switch ($urlKey)
            {
                case 'cancelOrder':
                    $url = \App\Config\CallBackstage::instance()->cancelOrder;
                    break;
                case 'confirmOrder':
                    $url = \App\Config\CallBackstage::instance()->confirmOrder;
                    break;
                default:
                    $url = '';
                    break;
            }

            $access_key = \App\Config\CallBackstage::instance()->key;
        }
        $data['trade_status'] = 'SUCCESS';
        $data['mysign'] = md5($createAccessKeyParam . 'SUCCESS' . $access_key);
         
        $i = 0;
        $result=['status'=>0];
        while($i<$repeatTime){
            $result_data = \App\Libs\Helper::curl_file_get_contents($url,$data);
            if($result_data=='success')
            {
                $result=['status'=>1];
                break;
            }
            $i++;
        }
        
        return $result;
    }
    
    
    /**
     * 调用后台
     * @param unknown $urlKey
     * @param unknown $data
     * @param unknown $createAccessKeyParam用来生成密钥的变量值
     */
    public static function callAdminywy($urlKey,$data,$createAccessKeyParam){
        $repeatTime =3;//失败重试次数
        if($urlKey == 'memberUp'){
            $url = \App\Config\CallBackstage::instance()->memberUp;
            $access_key = \App\Config\CallBackstage::instance()->key;
        }elseif($urlKey == 'sendCoupons'){
            $url = \App\Config\CallBackstage::instance()->sendCoupons;
            $access_key = \App\Config\CallBackstage::instance()->key;
        }
        
        $data['trade_status'] = 'SUCCESS';
        $data['mysign'] = md5($createAccessKeyParam . 'SUCCESS' . $access_key);
        
        $i = 0;
        $result=['status'=>0];
        while($i < $repeatTime){
            $result_data = \App\Libs\Helper::curl_file_get_contents($url,$data);
            if($result_data == 'success')
            {
                $result=['status'=>1];
                break;
            }
            $i++;
        }
    
        return $result_data;
    }
    
    /**
     * 二维数组排序
     * @param array $list
     * @param string $field
     * @param string $sortby
     * @return array|boolean
     */
    public static function listSortBy($list, $field, $sortby = 'asc')
    {
        if (is_array($list)) {
            $refer = $resultSet = array();
            foreach ($list as $i => $data)
                $refer[$i] = $data[$field];
                switch ($sortby) {
                    case 'asc': // 正向排序
                        asort($refer);
                        break;
                    case 'desc': // 逆向排序
                        arsort($refer);
                        break;
                    case 'nat': // 自然排序
                        natcasesort($refer);
                        break;
                }
                foreach ($refer as $key => $val)
                    $resultSet[] = $list[$key];
                    return $resultSet;
        }
        return false;
    }
    
    /**
     * 对象转数组
     * @param unknown $e
     * @return void|array
     */
    public static function objectToArray($e)
    {
        $e=(array)$e;
        foreach($e as $k=>$v){
            if( gettype($v)=='resource' ) return;
            if( gettype($v)=='object' || gettype($v)=='array' )
                $e[$k]=(array)self::objectToArray($v);
        }
        return $e;
    }
    
}